package com.weilele.leisure.time.ui.module.splash

import com.weilele.leisure.time.CommonHttp
import com.weilele.leisure.time.base.BaseVideoViewModel
import com.weilele.leisure.time.bean.PageByIdBean
import com.weilele.leisure.time.net.ApiInstance
import com.weilele.leisure.time.ui.module.main.ITEM_TYPE_AD
import com.weilele.leisure.time.ui.module.main.ITEM_TYPE_SEARCH
import com.weilele.mvvm.base.livedata.createStatusLiveData
import com.weilele.mvvm.base.livedata.success
import kotlinx.coroutines.Dispatchers

class SplashViewModel : BaseVideoViewModel() {

    val pageByIdData by lazy { createStatusLiveData<PageByIdBean>() }

    fun loginAndGetPageData(
        filter: List<String> = listOf(ITEM_TYPE_AD, ITEM_TYPE_SEARCH)/*过滤掉不想要的类型*/
    ) {
        pageByIdData.requestVideoApi(context = Dispatchers.IO) {
            //获取用户信息，登陆，获取后续调用接口需要的token
            CommonHttp.userInfo.success(CommonHttp.loadAppConfigAndLogin())
            val id = CommonHttp.homePages.firstOrNull()?.page?.id
            //获取首页数据
            ApiInstance.getPageById(id).apply {
                if (filter.isNotEmpty()) {
                    val result = this.result
                    result.components = removeItemType(result.components, filter)
                    result.childComponents = removeItemType(result.childComponents, filter)
                }
            }
        }
    }


    private fun removeItemType(
        filterList: List<PageByIdBean>?,
        filter: List<String>
    ): List<PageByIdBean>? {
        filterList ?: return null
        val newList = filterList.toMutableList()
        filterList.forEach {
            var isFilter = false
            filter.forEach { fil ->
                if (fil == it.type) {
                    isFilter = true
                    newList.remove(it)
                }
            }
            if (!isFilter) {
                //如果没有进行移除，检查子集合是否需要移除
                it.components = removeItemType(it.components, filter)
                it.childComponents = removeItemType(it.childComponents, filter)
            }
        }
        return newList
    }
}